import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface UserInfo {
  id: string;
  phone: string;
  nickname: string;
  access_token?: string;
  refresh_token?: string;
  is_wechat_bound?: boolean;
  avatarUrl?: string;
  openid?: string;
  email?: string;
  region?: string;
  is_lock?:boolean;
  wechatInfo?: {
    nickName: string;
    avatarUrl: string;
    gender: number;
    country: string;
    province: string;
    city: string;
    language?: string;
  };
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo | null>(null)
  const loading = ref(false)

  // 设置用户信息
  function setUserInfo(info: UserInfo | null) {
    // 如果有微信信息，合并到用户信息中
    if (info?.wechatInfo) {
      info.nickname = info.wechatInfo.nickName
      info.avatarUrl = info.wechatInfo.avatarUrl
      info.region = [
        info.wechatInfo.country,
        info.wechatInfo.province,
        info.wechatInfo.city
      ].filter(Boolean).join(' ')
    }
    
    userInfo.value = info
    if (info) {
      uni.setStorageSync('userInfo', info)
    } else {
      uni.removeStorageSync('userInfo')
    }
  }

  // 检查登录状态
  function checkLoginStatus(): boolean {
    // const storedUserInfo = uni.getStorageSync('userInfo')
    if (userInfo.value?.access_token) {
      return true
    }
    return false
  }

  // 退出登录
  function logout() {
    setUserInfo(null)
    uni.reLaunch({ url: '/pages/login/login' })
  }

  return {
    userInfo,
    loading,
    checkLoginStatus,
    setUserInfo,
    logout
  }
})